import { getRefreshToken } from "../api/login";
import config from "../config/index";
const BASE_URL = config.baseUrl;

let isRefreshing = false; // 是否正在刷新的标记
let requests = []; //重试队列

function request(url, params, method, isToken) {
  if (isToken === undefined) isToken = true;
  let _this = this;
  let token = wx.getStorageSync("token") || "";
  // console.log(url)
  // console.log(token)
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${BASE_URL}${url}`,
      method: method,
      data: params,
      timeout: 15000,
      header: {
        "Content-Type": "application/json",
        Authorization: token ? "Bearer " + token : "",
      },
      success: function (res) {
        if (res.statusCode == 200) {
          if (res.data.success == false) {
            if (url == "/skip/account/refresh.token") {
              console.log("刷新令牌过期---跳转到登录");
              setTimeout(() => {
                console.log("走到了这修改isRefreshing");
                isRefreshing = false; //防止isRefreshing一直未true，无法更新token
              }, 3000);
              wx.clearStorage()
              wx.switchTab({
                url: '/pages/home/home',
              })
              // wx.navigateTo({
              //   url: "/pages/login/login",
              // });
              return;
            } else {
              wx.showToast({
                title: res.data.msg, // 标题
                icon: "none", // 图标类型，默认success
                duration: 1500, // 提示窗停留时间，默认1500ms
              });
            }
            resolve(res.data);
          } else {
            resolve(res.data);
          }
        } else if (res.statusCode == 401) {
          console.log("isRefreshing", isRefreshing);
          new Promise((resolve2) => {
            // 用函数形式将 resolve 存入，等待刷新后再执行
            requests.push((token) => {
              resolve(request(url, params, method, isToken));
            });
          });
          if (!isRefreshing) {
            //成功状态
            console.log("token过期");
            isRefreshing = true; //第一个请求后，后面请求都不进入执行请求
            // debugger;
            //调用刷新token的接口
            if (wx.getStorageSync("tokenData") && JSON.parse(wx.getStorageSync("tokenData")).refresh_token && JSON.parse(wx.getStorageSync("tokenData")).refresh_token !== '') {
              let data = {
                refreshToken: wx.getStorageSync("tokenData")
                  ? JSON.parse(wx.getStorageSync("tokenData")).refresh_token
                  : "",
              };
              getRefreshToken(data).then((res2) => {
                if (res2.success) {
                  console.log("getRefreshToken-res2: ", res2);
                  var obj = res2.data;
                  wx.setStorage({
                    key: "token",
                    data: obj.access_token,
                  });
                  wx.setStorage({
                    key: "tokenData",
                    data: JSON.stringify(obj),
                  });
                  requests.forEach((cb) => cb(data.token));
                  requests = []; // 重新请求完清空
                  // isRefreshing = false; //第一个请求后，后面请求都不进入执行请求
                  setTimeout(() => {
                    console.log("修改isRefreshing");
                    isRefreshing = false; //防止isRefreshing一直未true，无法更新token
                  }, 1000);
                } else {
                  setTimeout(() => {
                    console.log("修改isRefreshing---跳转到登录");
                    isRefreshing = false; //防止isRefreshing一直未true，无法更新token
                  }, 1000);
                  wx.clearStorage()
                  wx.switchTab({
                    url: '/pages/home/home',
                  })
                  // wx.navigateTo({
                  //   url: "/pages/login/login",
                  // });
                }
              });
            } else {
              wx.clearStorage()
              wx.switchTab({
                url: '/pages/home/home',
              })
            }

          } else {
            console.log("走到了这", isRefreshing);
            // setTimeout(() => {
            //   console.log("走到了这修改isRefreshing");
            //   isRefreshing = false; //防止isRefreshing一直未true，无法更新token
            // }, 50);
          }
        } else {
          // 请求服务器成功，但是由于服务器没有数据返回，
          //此时无code。会导致这个空数据
          // 不下去，导致报错，所以还是要resolve下，这样起码有个返回值，
          //不会被阻断在那里执行不下去！
          resolve(res.data);
          wx.showToast({
            title: res.data.msg, // 标题
            icon: "none", // 图标类型，默认success
            duration: 1500, // 提示窗停留时间，默认1500ms
          });
        }
      },
      fail: function (err) {
        console.log();
        reject(err);
      },

      complete: function () { },
    });
  });
}
module.exports = {
  request: request,
};
